/*************************************************
Name : CaseUploadController
Created By : dthekumparampil
Created Date : Jan 29, 2013
Description :   Controller Class to upload Cases to database. 
                                It takes a CSV (Windows format) as input and creates cases based on the information provided and links them to Account or Lead based on the ID provided.
******************************
Modified By : dthekumparampil
Modified Date : Feb 4, 2013
Modification :  Removed all the ApexPage Error messages and replaced them with message that get saved in the UploadResults 
                                and get displayed in VF.
******************************
Modified By : dthekumparampil
Modified Date : Feb 15, 2013
Modification :  Logic to handle empty priority field added.

******************************
Modified By : dthekumparampil
Modified Date : Feb 21, 2013
Modification :  the upload results are getting saved in Case_Upload_Log__c. 
*************************************************/

public with sharing class CaseUploadController {
        
    public CaseUploadController(ConsoleHomeController_AC controller){
        activateUploadFlag=false;
        String ProfileName = [select id, name from profile where id=:UserInfo.getProfileId() LIMIT 1].name;
        If(ProfileName=='West Case Management - Case Manager'){
                activateUploadFlag=true;
        }
        resultVisibilityFlag=false;
    }
        
    public CaseUploadController(){
        activateUploadFlag=false;
        String ProfileName = [select id, name from profile where id=:UserInfo.getProfileId() LIMIT 1].name;
        If(ProfileName=='West Case Management - Case Manager'){
                        activateUploadFlag=true;
        }
        resultVisibilityFlag=false;
    }
        
    public String csvFileName{get;set;}
    public transient String fileToString {get;set;}
    public transient blob csvFileContent{get;set;}
     transient String[] fileLines = new String[]{};
    public List<Case> casesToUpload;
    public list<ResultSet> UploadResults = new list<ResultSet>();
    public boolean resultVisibilityFlag {get;set;}
    public boolean activateUploadFlag{get; set;}
    public Integer successCount {get; set;}
    public Integer failureCount {get; set;}
    public String displayString{get; set;}
    list <Case_Upload_Log__c> uploadLog = new list <Case_Upload_Log__c>();
    public Decimal uploadNumber = 1;
    
    
   
   //--Start --Changes  done  by allam venkata Suneetha  
    public Map<string, string> idsList = new Map<string, string>() ;
    Set<string> setIdsList = new Set<string>();
    public Map<string, string> leadsIdList = new Map<string, string>() ;
    public Map<string, string> accountsIdList = new Map<string, string>() ;
   //--end--/
   /*Getting the last upload number*/
  public void getUploadNumber()
  {
     
        uploadLog = [select Upload_Number__c, CreatedDate from Case_Upload_Log__c order by createddate desc LIMIT 1 ];
        if(uploadLog.size()>0){
            uploadNumber = 1 + uploadLog[0].Upload_Number__c;
        }
        uploadLog.clear();
  }
  
    /****Reading the CSV file ****/
    public Pagereference readFile(){
        
        
        try
        {
        
        uploadLog.clear();
        UploadResults.clear();
        resultVisibilityFlag=false;
        successCount=0;
        failureCount=0;
        
        
        
          /*Getting the last upload number*/
          getUploadNumber();
        
        
           if(csvFileContent!=null){
        
                /*Getting all the case names for checking in uploading records*/
                Map<String,String> caseNameMap = new Map<String, String>();
                list<West_Case_Names__c> westCaseNames = [select id,name from West_Case_Names__c]; 
                for (integer index=0;index<westCaseNames.size(); index++){
                    caseNameMap.put(westCaseNames[index].name,westCaseNames[index].id);
                }
        
                String caseRecordType = Schema.Sobjecttype.Case.getRecordTypeInfosByName().get('West - Support').getRecordTypeId();
                
                fileToString=csvFileContent.toString();
                fileLines=fileToString.split('\n');
              
                
                 for(Integer index=1; index<fileLines.size(); index++){
                    
                    String[] inputFields = new String[]{};
                    inputFields=fileLines[index].split(',');
                    
                    /*Enter an empty priority in case priority is not specified in file*/
                    if(inputFields.size()<5){
                        inputFields.add(' ');
                    }

                        
                    /*Trimming the inputField values*/
                    for (Integer innerIndex=0; innerIndex< inputFields.size(); innerIndex++){
                        inputFields[innerIndex] = inputFields[innerIndex].trim();
                        if(inputFields[innerIndex]=='' && innerIndex<4){
                            ResultSet tempResultSet = new ResultSet(fileLines[index],'ERROR Missing Mandatory Field in Row:'+index+' Column: '+innerIndex+1);
                            UploadResults.add(tempResultSet);
                            
                            /*Code to store result in Case_Upload_Log__c*/
                            setUploadLog(inputFields, 'ERROR Missing Mandatory Field in Row:'+index+' Column: '+innerIndex+1);
                            //insert uploadLog;
                            //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'ERROR Missing Mandatory Field in Row:'+index));
                            csvFileContent=null;
                            resultVisibilityFlag=true;
                            displayString = 'Error In File';
                            return null;
                        }
                    }

                    /*Checking if Case Name is matching with database ones*/
                    if(!caseNameMap.containsKey(inputFields[1])){
                        ResultSet tempResultSet = new ResultSet(fileLines[index],'ERROR CSV File Row: '+index+' Faulty Case Name: '+inputFields[1]);
                        UploadResults.add(tempResultSet);
                        
                        /*Code to store result in Case_Upload_Log__c*/
                        setUploadLog(inputFields, 'ERROR CSV File Row: '+index+' Faulty Case Name: '+inputFields[1]);
                        insert uploadLog;
                        
                        resultVisibilityFlag=true;
                        //Apexpages.Message errorMessage = new Apexpages.Message(ApexPages.severity.ERROR,'ERROR CSV File Row: '+index+'        Faulty Case Name: '+inputFields[1]);
                        //Apexpages.addMessage(errorMessage);
                        csvFileContent=null;
                        displayString = 'Error In File';
                                               return null;
                    }
                    
                    
                    // Indentifying Unique ids and making list
                      if (idsList.get(inputFields[0].trim()) ==null)
                     {
                           idsList.put(inputFields[0].trim(),inputFields[0].trim());
                           setIdsList.Add(inputFields[0].trim());
                      }
                        
                 }
                 
        
                //Account ids & Lead Ids identification process 
                CheckIds();
                if (fileLines.size()>1998)
               {
                              displayString = 'Error:File is too large';
                              resultVisibilityFlag=true;
                              return null;              
               }
                
                casesToUpload =new list<Case>();
                
                //UploadResults.clear();
                /*Record wise traversal*/
                for(Integer index=1; index<fileLines.size(); index++){
                    String[] inputFields = new String[]{};
                    inputFields=fileLines[index].split(',');
                    
                    
                    /*Creating Cases to upload*/
                    Case tempCase = new Case();
                    
                    /*In the below code the id in CSV file is checked against the records in Account and then in Lead*/
                    //--Start Modifications  by  suneetha  on 02-05-2013
                     ID Accountid;
                    if (accountsIdList!=null)
                    {
                       Accountid=accountsIdList.get(inputFields[0].trim());
                    }
                   Id Leadid;
                      if (leadsIdList!=null)
                    {
                     Leadid =leadsIdList.get(inputFields[0].trim());
                    }
                     
                    
                    if(Accountid!=null){
                        tempCase.AccountId =  Accountid;
                        
                     }
                    else if ( Leadid!= null)
                    {
                            tempCase.Lead__c = Leadid;
                    }
                    else{
                        /*Code to store result in Case_Upload_Log__c*/
                        setUploadLog(inputFields, 'ERROR in Row '+index+' Please check this ID:  '+ inputFields[0].trim());
                       /// insert uploadLog;
                        
                        ResultSet tempResultSet = new ResultSet(fileLines[index],'ERROR in Row '+index+' Please check this ID:  '+inputFields[0]);
                        UploadResults.add(tempResultSet);
                        //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'ERROR in Row'+index+' Please check this ID:  '+inputFields[0]));
                        csvFileContent=null;
                        resultVisibilityFlag=true;
                        displayString = 'Error In File';
                        return null;
                        //continue;
                     }
                      //--end Modifications  by  suneetha  on 02-05-2013
                    tempCase.Case_Name__c = inputFields[1];
                    tempCase.Subject = inputFields[2];
                    tempCase.Description = inputFields[3];
                    tempCase.RecordTypeId = caseRecordType;
                    tempCase.West_Case_Priority_Set__c = false;
                    System.debug('4th field is :'+inputFields[4]+':');
                    if(inputFields[4].length()>0 && inputFields[4]!='' && inputFields[4].isNumeric()){
                            tempCase.Priority = inputFields[4];
                            tempCase.West_Case_Priority_Set__c = true;
                    }
                    casesToUpload.add(tempCase);
                    /*Code to store result in Case_Upload_Log__c*/
                    setUploadLog(inputFields, 'null');
                }//// end of inputfields
               
             
                Database.Saveresult[] insertResults;
                   system.debug('>>>>>the size of insertresults1: '+ casesToUpload.size());
                insertResults = Database.insert(casesToUpload, false);
                
                system.debug('>>>>>the size of insertresults: '+insertResults.size());
   
                for(Integer index=0; index<(fileLines.size()-1); index++){
                    if(insertResults[index].isSuccess()){
                        uploadLog[index].Result__c = 'Success: '+insertResults[index].getId();
                        system.debug('//////////Success record: '+fileLines[index+1]+'\nStatus: '+insertResults[index].getId());
                        //ResultSet tempResultSet = new ResultSet(fileLines[index+1],'Success: '+insertResults[index].getId());
                        ResultSet tempResultSet = new ResultSet('Row: '+(index+1),'Success: '+insertResults[index].getId());
                        UploadResults.add(tempResultSet);
                        successCount++;
                    }
                    else if(!insertResults[index].isSuccess()){ 
                        uploadLog[index].Result__c = 'Failed: ID not found in Salesforce';
                        system.debug('//////////ERROR record: '+fileLines[index+1]+'\nIndex of for loop: '+index+'\n');
                        //ResultSet tempResultSet = new ResultSet(fileLines[index+1],'Failed: ID not in Salesforce');
                        ResultSet tempResultSet = new ResultSet('Row: '+(index+1),'Failed: ID not found in Salesforce');
                        UploadResults.add(tempResultSet);
                        failureCount++;
                    }
                }
            resultVisibilityFlag=true;
            insert uploadLog;
            displayString = 'Success: '+successCount+'  Failure: '+failureCount;
            csvFileContent=null;
           return null;
        }
        }
        catch(exception ex){
            displayString = 'Error:File is too large';
        }        
        return null;
    }
    
    
      //--Added  by  suneetha  on 02-05-2013
    public void CheckIds()
    {
        system.debug('tep 3: ' +  setIdsList);
            list<Account> foundInAccount = [select id, Account_Id__c from Account where Account_Id__c IN :(setIdsList)];
            list <Lead> foundInLead = [select id, Lead_Id__c, IsConverted from Lead where IsConverted = false AND (Lead_Id__c IN :(setIdsList))];
            string idstr;
            
                    if(foundInAccount.size()>0){
                        for(Account accountObj: foundInAccount)
                        {
                            idstr=accountObj.id;
                            accountsIdList.put(accountObj.Account_Id__c,idstr);
                        }
                      }
                     if(foundInLead.size()>0){
                            for(Lead leadObj: foundInLead)
                            {
                                   idstr=leadObj.id;
                                    leadsIdList.put(leadObj.Lead_Id__c,idstr);
                            }
                       }
                       
                 //   system.debug('tep 3: ' +  foundInAccount);
            //  system.debug('step 4: ' +  leadsIdList);
                  
    }
    /****Inner Class created to store & display result****/
    public class ResultSet{
        public String inputRecord {get;set;}
        public String status {get;set;}
        
        public ResultSet(String inputRecord1, String status1){
            inputRecord = inputRecord1;
            status = status1;
        }
    }
        
    /****Returning ResultSet ****/
    public list<ResultSet> getUploadResults(){
        if(UploadResults!=NULL && UploadResults.size()>0){
        return UploadResults;
                }
        else{
                return null;
        }
    }
    
    /****Toggling the Upload activation Flag ****/
    public PageReference activateUpload(){
        activateUploadFlag=true;
        return null;
    }
    public PageReference deactivateUpload(){
        activateUploadFlag=false;
        return null;
    }
    /****Closing results ****/
    public Pagereference closeResults(){
        //activateUploadFlag=false;
        UploadResults.clear();
        return null;
    }
    
    /****Set Upload Log ****/
    private void setUploadLog(String[] inputFields, String Message){
        Case_Upload_Log__c tempUploadLog = new Case_Upload_Log__c(Name = 'Upload'+uploadNumber, Upload_Number__c = uploadNumber, Result__c = Message, 
                                                                    Salesforce_ID__c = inputFields[0], Case_Name__c = inputFields[1], Subject__c = inputFields[2], 
                                                                    Description__c = inputFields[3], Priority__c = inputFields[4]);
        uploadLog.add(tempUploadLog);
    }
    
    //public Decimal getuploadNumber(){
    //  return uploadNumber;
    //}
    
    public String getReportUrl(){
        Report uploadReport = [select id, name from report where name='West Case Upload Results' LIMIT 1];
        return '/'+uploadReport.id+'?pv0='+uploadNumber;
    }
}